from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
# from common.sq_log import Log
from common.com_time import Time
import threading
import datetime


class Scheduler:
    """
    定时任务管理工具
    """
    ap_scheduler = BlockingScheduler(executors={
        'default': ThreadPoolExecutor(6),
        'processpool': ProcessPoolExecutor(3)
    }, timezone='Asia/Shanghai')

    status = False
    lock = threading.Lock()

    @classmethod
    def add_interval(cls, interval_func, seconds):
        """
        添加间隔定时任务
        :param interval_func: 定时任务函数
        :param seconds: 间隔时间，单位-秒
        :return: None
        """
        cls.ap_scheduler.add_job(func=interval_func, trigger="interval",
                                 start_date="1900-1-1 00:00:00",
                                 next_run_time=Time.current_datetime_str(),
                                 end_date="2100-1-1 00:00:00", seconds=seconds, misfire_grace_time=None)
        # Log.info(f"scheduler add_interval {interval_func}")

    @classmethod
    def add_crontab(cls, crontab_func, hour=None, minute=None):
        """
        添加定点定时任务
        :param crontab_func: 定时任务函数
        :param hour: 定时任务每天开始时间，单位-小时
        :param minute: 定时任务每天开始时间，单位-秒
        :return: None
        """
        cls.ap_scheduler.add_job(func=crontab_func, trigger="cron", hour=hour, minute=minute)
        # Log.info(f"scheduler add_crontab {crontab_func}")

    @classmethod
    def start(cls):
        """
        启动已添加的定时任务
        :return:
        """
        with cls.lock:
            if not cls.status:
                # Log.info("scheduler start")
                cls.status = True
                cls.ap_scheduler.start()


def play():
    print(f'{datetime.datetime.now()}')


if __name__ == '__main__':
    Scheduler.add_interval(interval_func=play, seconds=3)
    Scheduler.ap_scheduler.start()
